package com.wt.admin.service.ai.impl.agents;

import cn.hutool.core.util.ObjectUtil;
import com.wt.admin.domain.dto.ai.AgentsInfoDTO;
import com.wt.admin.domain.entity.ai.MCPEntity;
import com.wt.admin.domain.entity.ai.ModelConfigEntity;
import com.wt.admin.service.ai.impl.mcp.MCPStart;
import io.micrometer.observation.ObservationRegistry;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.model.tool.ToolCallingManager;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.ai.ollama.management.ModelManagementOptions;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("Ollama")
public class OllamaBuilder implements AgentsBuilderService{

    @Resource
    MCPStart mcpStart;

    @Override
    public AgentsManager.Agent builder(AgentsInfoDTO agents, ModelConfigEntity model, List<MCPEntity> mcpEntities) {
        // 查询模型信息
        var ollamaApi = new OllamaApi(model.getBaseUrl());
        OllamaChatModel ollama = new OllamaChatModel(ollamaApi , OllamaOptions.builder()
                .model(model.getModel())
                .temperature(0.7)
                .build(),ToolCallingManager.builder().build(), ObservationRegistry.NOOP, ModelManagementOptions.defaults());

        ChatClient.Builder builder = ChatClient.builder(ollama)
                .defaultSystem("""
                        你是%s,%s
                        """.formatted(agents.getName(), agents.getBackground()));
        mcpEntities.forEach(mcpEntity -> {
            ToolCallbackProvider[] toolCallbackProvider = getToolCallbackProvider(mcpStart,mcpEntity);
            if(ObjectUtil.isEmpty(toolCallbackProvider)){
                return;
            }
            builder.defaultTools(toolCallbackProvider);
        });
        // 不建议使用工具，1. 很多大模型不支持 2. 不方便与外部建立连接
//        ToolCallback[] dateTimeTools = ToolCallbacks.from(new DateTimeTools(),new WeatherTools());

        return new AgentsManager.Agent( builder.build(), null);
    }

}
